#include <unistd.h>

#include "../code/http/HttpServer.h"

int main()
{
    EventLoop loop{};
    HttpServer server(&loop, InetAddress(8633), TcpServer::ListenOption::ReusePort, "HttpsServer", true);

    // SSL配置
    // 在test/下

    // 生成自签证书：openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout key.pem -out cert.pem

    // 测试证书或服务端
    // openssl s_server -accept 8633 -cert cert.pem -key key.pem -www
    // openssl s_client -connect 127.0.0.1:8633 -CAfile ./cert.pem -msg -debug -state
    // openssl s_client -connect 127.0.0.1:8633 -CAfile ./cert.pem

    std::string certFile = "../cert.pem"; // build/可执行文件的相对路径
    std::string privateKeyFile = "../key.pem";
    std::cout << "Load certificate from: " << certFile << std::endl;
    if (::access(certFile.c_str(), R_OK) != 0)
    {
        std::cerr << "Cannot read certificate file: " << certFile << std::endl;
        return -1;
    }
    std::cout << "Load private key from: " << privateKeyFile << std::endl;
    if (::access(privateKeyFile.c_str(), R_OK) != 0)
    {
        std::cerr << "Cannot read private key file: " << privateKeyFile << std::endl;
        return 1;
    }

    SslConfig sslConfig{};
    sslConfig.setCertificateFile(certFile);
    sslConfig.setPrivateKeyFile(privateKeyFile);
    sslConfig.setProtocolVersion(SslVersion::Ssl13); // 注意版本
    server.setSslConfig(sslConfig);

    // 路由
    server.Get("/", [](const HttpRequest &req, HttpResponse *res)
               {
            res->setStatusCode(HttpResponse::StatusCode::Ok200);
            res->setStatusMessage("OK");
            res->setContentType("text/plain");
            res->addHeader("Server", "YeZhe");
            res->setBody("Hello, World!\n"); });

    server.start();
    loop.start();

    return 0;
}